// src/common/utils/request-url.util.ts
import { Request } from "express";

export class RequestUrlUtil {
    /**
     * 获取完整的请求 URL (如: http://localhost:7001/api/v1/uploads)
     * @param req 请求对象
     */
    static getFullUrl(req: Request): string {
        return `${this.getProtocol(req)}://${this.getHost(req)}${req.originalUrl}`;
    }

    /**
     * 获取基础 URL (如: http://localhost:7001)
     * @param req 请求对象
     */
    static getBaseUrl(req: Request): string {
        return `${this.getProtocol(req)}://${this.getHost(req)}`;
    }

    /**
     * 获取协议 (http 或 https)
     * @param req 请求对象
     */
    static getProtocol(req: Request): string {
        // 处理反向代理情况
        const forwardedProto = req.headers["x-forwarded-proto"];
        if (Array.isArray(forwardedProto)) {
            return forwardedProto[0];
        }
        return forwardedProto || req.protocol;
    }

    /**
     * 获取主机地址 (如: localhost:7001)
     * @param req 请求对象
     */
    static getHost(req: Request): string {
        // 处理反向代理情况
        const forwardedHost = req.headers["x-forwarded-host"];
        if (forwardedHost) {
            return Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost;
        }
        return req.get("host") || "";
    }

    /**
     * 获取请求路径 (如: /api/v1/uploads)
     * @param req 请求对象
     */
    static getPath(req: Request): string {
        return req.originalUrl;
    }

    /**
     * 获取请求的域名部分 (如: localhost)
     * @param req 请求对象
     */
    static getDomain(req: Request): string {
        const host = this.getHost(req);
        return host.split(":")[0];
    }

    /**
     * 获取请求的端口号 (如: 7001)
     * @param req 请求对象
     */
    static getPort(req: Request): string {
        const host = this.getHost(req);
        const parts = host.split(":");
        return parts.length > 1 ? parts[1] : this.getProtocol(req) === "https" ? "443" : "80";
    }
}
